package com.yyge.controller.front.merchandiser;


import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.yyge.common.enums.AckCode;
import com.yyge.common.vo.resp.PageResp;
import com.yyge.common.vo.resp.R;
import com.yyge.controller.admin.mapstruct.MerchandiserConverter;
import com.yyge.controller.front.mapstruct.MerchandiserConvert;
import com.yyge.controller.front.merchandiser.req.MerchandiserAddReq;
import com.yyge.controller.front.merchandiser.req.MerchandiserReq;
import com.yyge.controller.front.merchandiser.resp.EnterpriseProcessResp;
import com.yyge.controller.front.merchandiser.resp.FrontMerchandiserResp;
import com.yyge.controller.front.merchandiser.resp.MerchandiserResp;
import com.yyge.entity.EnterpriseProcess;
import com.yyge.entity.Merchandiser;
import com.yyge.service.EnterpriseProcessService;
import com.yyge.service.MerchandiserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.lang.reflect.Array;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Api(tags = "前端-商家API")
@RestController
@RequestMapping(value = "/front/enterprise")
public class FrontMerchandiserController {
    @Autowired
    private MerchandiserService merchandiserService;

    @Autowired
    private EnterpriseProcessService  enterpriseProcessService;

    @ApiOperation(value = "商家注册")
    @PostMapping(value = "/add")
    public R register(@RequestBody @Valid MerchandiserAddReq req){
         // 验证号码是否已经注册过了
        LambdaQueryWrapper<Merchandiser> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Merchandiser::getLoginName,req.getLoginName());
        long count=merchandiserService.count(wrapper);
        if(count>0){
            return R.build(AckCode.EXISTS_VALUE);
        }

        Merchandiser merchandiser = MerchandiserConverter.MAPPER.convert(req);
        merchandiser.setCreateTime(new Date());
        merchandiser.setUpdateTime(new Date());
        merchandiser.setCreateBy(req.getName());
        merchandiser.setUpdateBy(req.getName());
        merchandiser.setStatus("0");
        String hashpw = BCrypt.hashpw(req.getLoginPwd());
        merchandiser.setLoginPwd(hashpw);
        boolean save = merchandiserService.save(merchandiser);

        return save==true?R.ok("商家注册成功"):R.build(AckCode.SYSTEM_PARAM_FAIL);
    }

    @ApiOperation(value = "查询审核记录")
    @GetMapping(value = "/process/{loginName}")
    public R search( @PathVariable(value = "loginName") String loginName){
        if (StrUtil.isBlank(loginName)){
            return R.build(AckCode.SYSTEM_PARAM_FAIL);
        }

        //检查格式对不对
        final String  regex="^0?(13|15|17|18|14|19)[0-9]{9}$";

        //创建表达式
        Pattern pattern = Pattern.compile(regex);
        //创建匹配模型
        Matcher matcher = pattern.matcher(loginName);

        if(!matcher.matches()){
            return R.build(AckCode.ENTERPRISE_PHONE_ERROR);
        }

        //查询数据
        Merchandiser merchandiser = new Merchandiser();
        merchandiser.setPhone(loginName);
        QueryWrapper<Merchandiser> queryWrapper=new QueryWrapper<>(merchandiser);
        Merchandiser db  = merchandiserService.getOne(queryWrapper);
        if(Objects.isNull(db)){
            return R.build(AckCode.NOT_FOUND_DATA);
        }

        Map<String,Object> dataMap=new HashMap<>();
        FrontMerchandiserResp convert = MerchandiserConvert.INSTANCE.convert(db);
        dataMap.put("merchandiser",convert);

        //enterpriseProcessList  历史审核记录
        List<Long> ids=new ArrayList<>();
        ids.add(db.getId());
        List<EnterpriseProcess> enterpriseProcess =this.enterpriseProcessService.listByIds(ids);

        //转换对象
        List<EnterpriseProcessResp> enterpriseProcessResps = MerchandiserConvert.INSTANCE.convert(enterpriseProcess);


        //是否要添加正在审核中的状态
        if(db.getStatus().equals("0")){
         EnterpriseProcessResp resp=new EnterpriseProcessResp();
            //模拟一个主键
            resp.setId(IdUtil.getSnowflakeNextId());
            resp.setTenantId(db.getId());
            resp.setStatus("0");
            //第一次提交
            if(Objects.isNull(db.getUpdateTime())){
                resp.setCreateTime( db.getCreateTime());
            }else {
                resp.setCreateTime(db.getUpdateTime());
            }
            resp.setDescription("审核中，请耐心等待...");

            enterpriseProcessResps.add(0, resp);
        }

        dataMap.put("enterpriseProcessList",enterpriseProcessResps);
        return R.okHasData(dataMap);
    }

    @ApiOperation(value = "分页查询")
    @GetMapping(value = "/data")
    public R<PageResp<MerchandiserResp>> search(@Valid MerchandiserReq req){
        PageInfo<MerchandiserResp> pageInfo=this.merchandiserService.frontSearch(req);
        System.out.println(pageInfo.getList());
        PageResp<MerchandiserResp>  resp=new PageResp<>();
        resp.setTotal(pageInfo.getTotal());
        resp.setRows(pageInfo.getList());
        return R.okHasData(resp);
    }

    @ApiOperation(value = "根据主键查询")
    @GetMapping(value = "/findById")
    public R<MerchandiserResp> findById(@Valid MerchandiserReq req){

        MerchandiserResp merchandiserResp = merchandiserService.findById(req);
        System.out.println(req);
        System.out.println("------11");
        //PageInfo<MerchandiserResp> pageInfo=this.merchandiserService.frontSearch(req);
        //System.out.println(pageInfo.getList());

//        PageResp<MerchandiserResp>  resp=new PageResp<>();
//        resp.setTotal(pageInfo.getTotal());
//        resp.setRows(pageInfo.getList());
        return R.okHasData(merchandiserResp);
        //return R.okHasData(resp);
    }
}
